<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;

class JsonArray implements Rule
{
    protected $rules, $errorMessage;

    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct($rules)
    {
        $this->rules = $rules;
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $list = json_decode($value, true);

        if(empty($list)) {
            $this->errorMessage = 'json数据格式错误';
            return false;
        }

        $result = $this->validatorJsonArray($list);
        return $result;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return 'json数据验证失败-'.$this->errorMessage;
    }

    public function validatorJsonArray($data)
    {
        $rules = $this->rules;

        if(!is_array($data)) {
            return false;
        }

        foreach($data as $key => $item) {
            if(count(array_filter(array_keys($data), 'is_string')) > 0) {
                $validator = Validator::make([$key=> $item], [$key => $rules[$key]]);

                if($validator->fails()) {
                    $errorList = $validator->errors()->getMessages();
                    foreach($errorList as $errors) {
                        foreach($errors as $error) {
                            if($error != 'validation.j_s_o_n') {
                                $this->errorMessage = $error;
                            }
                        }
                    }

                    return false;
                }
            }
            else {
                $result = $this->validatorJsonArray($item);

                if($result === false) {
                    return false;
                }
            }
        }

        return true;
    }
}
